#
#  Copyright (C) 2009 GSyC/LibreSoft
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
#    Author : Jose Antonio Santos Cadenas <jcaden __at__ gsyc __dot__ es>
#

import string

def do_search (type, fields, terms, exact=False):
    """
    Finds the objects in type whose fields include terms
    
    @param typs: the model type
    @param fields: the fields that will be looked
    @param terms: the search terms
    @param exact: terms must be exact
    """
    result = type.objects.none()
    terms = string.split(terms)
    for f in fields:    
        r = type.objects.all()
        for term in terms:
            if exact:
                r = r.__and__(type.objects.filter(**{"%s" % f: term}))
            else:
                r = r.__and__(type.objects.filter(**{"%s__icontains" % f: term}))
        result = result.__or__(r)
    return result
        
def do_multi_search (types_fields, terms, viewer=None, exact=False):
    """
    This receives an array of dictionaries with types and terms 
    """
    results = {}
    for tf in types_fields:
        if viewer:
            try:
                model_search = tf["type"].objects.allowed(viewer.id).__and__(do_search(tf["type"], tf["fields"], terms, exact))
            except:
                return False
        else:
            model_search = do_search(tf["type"], tf["fields"], terms, exact)
        results[tf["type"]._meta.verbose_name] = model_search
    return results
